<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button
            class="filter-item marginRB10"
            icon="el-icon-plus"
            type="primary"
            @click="handleCreate()"
          >添加
          </el-button>
        </el-row>
      </div>
      <div class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          style="margin-bottom: 20px"
        >
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="图片" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 400px; max-height: 400px"/>
                <img slot="reference" :src="scope.row.picture" alt="" preview="3" style="width: 80px"/>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="是否免费" prop="is_free">
            <template slot-scope="{row}">
              <el-tag v-show="row.is_free == 1" type="info">免费</el-tag>
              <el-tag v-show="row.is_free == 0" type="primary">付费</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="出售状态" prop="sell_status">
            <template slot-scope="{row}">
              <el-tag v-show="row.sell_status === 1" type="success">上架</el-tag>
              <el-tag v-show="row.sell_status === 2" type="info">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="添加时间" prop="add_time"></el-table-column>

          <el-table-column label="操作" min-width="180">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button
              >
              <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          v-show="total > 0"
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :model="form"
        :rules="rules"
        label-position="right"
        label-width="120px"
        width="300px"
      >
        <el-form-item label="图片" prop="picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="pictureList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handlePropPictureRemove"
            :on-success="handlePropPictureSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="效果图" prop="effect_picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="pictureList_eff"
            :http-request="customizeUpload"
            :on-success="handleEffectSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传效果图</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input
            v-model="form.name"
            maxlength="20"
            placeholder="请输入名称"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="是否免费" prop="is_free">
          <el-radio-group v-model="form.is_free">
            <el-radio :label="0" border>付费</el-radio>
            <el-radio :label="1" border>免费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出售状态" prop="sell_status">
          <el-radio-group v-model="form.sell_status">
            <el-radio :label="1" border>上架</el-radio>
            <el-radio :label="2" border>下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <section v-show="form.is_free == 0">
          <el-form-item
            v-for="(item, index) in form.day_price"
            :key="index"
            label="指定天数费用"
            prop="day_price"
          >
            <section class="flex items-center mb-4">
              <section class="mr-8">
                <span>使用天数： </span>
                <el-input-number v-model="item.day" :max="1e10" :min="0" label="使用天数"/>
              </section>

              <section class="mr-8">
                <span>费用： </span>
                <el-input-number v-model="item.price" :max="1e10" :min="0" label="费用"/>
              </section>
              <el-button type="danger" @click="handleDelItem(index)">删除该条</el-button>
            </section>

          </el-form-item>
          <el-button style="transform: translateX(120px)" type="success" @click="handleAddNewItem">新增一条</el-button>
        </section>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, postAddData, putEditData } from '@/api/room/background'

export default {
  data() {
    return {

      confirmBtn: false,

      pictureList: [],
      pictureList_eff: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      menuList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        id: '',
        picture: '',
        name: '',
        effect_picture: '',
        is_free: 0,
        sell_status: 1,
        day_price: [
          { day: 0, price: 0 }
        ]
      },
      rules: {
        picture: [{ required: true, message: '请选择图片', trigger: 'change' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        effect_picture: [{ required: true, message: '请上传缩略图', trigger: 'blur' }],
        is_free: [{ required: true, message: '请选择是否免费', trigger: 'blur' }],
        sell_status: [{ required: true, message: '请选择出售状态', trigger: 'blur' }],
        day_price: [{ type: 'array', required: true, message: '请添加天数费用', trigger: 'blur' }]
      },
      row_id: undefined
    }
  },
  created() {
    this.getList()
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      // const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传PNG格式的图片!')
      }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!')
      // }
      return isJPG
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handlePropPictureSuccess() {
      this.form.picture = this.ossLastImgUrl
      this.pictureList = [{ url: this.ossLastImgUrl }]
    },
    handleEffectSuccess() {
      this.form.effect_picture = this.ossLastImgUrl
      this.pictureList_eff = [{ url: this.ossLastImgUrl }]
    },

    handlePropPictureRemove(res) {
      this.form.picture = undefined
      this.pictureList = []
    },

    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      listData(urlData).then((response) => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },

    /* 新增一条  */
    handleAddNewItem() {
      this.form.day_price.push({ day: 0, price: 0 })
    },
    /* 删除一条 */
    handleDelItem(index) {
      this.form.day_price.splice(index, 1)
    },
    handleUpdate(row) {
      this.row_id = row.id
      this.form.picture = row.picture
      this.form.effect_picture = row.effect_picture
      this.form.sell_status = row.sell_status
      this.form.is_free = row.is_free
      this.form.day_price = row.room_background_products_price.map(item => ({ day: item.day, price: item.price }))
      this.pictureList = [{ url: row.picture }]
      this.pictureList_eff = [{ url: row.effect_picture }]
      this.form.name = row.name
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleDelete(row) {
      let data = { ids: row.id.toString() }
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    },
    allDel() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      let delNum = []
      this.$refs.dataList.selection.forEach((k) => {
        delNum.push(k.id)
      })
      if (delNum.length === 0) {
        return
      }
      let data = { ids: delNum.toString() }
      deleteData(data).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    submitForm() {
      if (this.confirmBtn) return
      this.$refs['dataForm'].validate((valid) => {
        if (valid && this.dialogStatus === 'create') {
          this.form.day_price = JSON.stringify(this.form.day_price)
          this.confirmBtn = true
          let formData = new FormData()
          for (let item in this.form) {
            this.form[item] !== undefined && formData.append(item, this.form[item])
          }

          postAddData(formData).then((response) => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.resetForm()
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
            } else {
              this.confirmBtn = false
            }
            /* 出现了一些很麻烦且不影响功能的BUG， 先放一放 */
            console.clear()
          })
        } else if (valid && this.dialogStatus === 'update') {
          this.confirmBtn = true
          const tempForm = JSON.parse(JSON.stringify(this.form))
          tempForm.day_price = JSON.stringify(tempForm.day_price)
          putEditData(this.row_id, tempForm).then((response) => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.confirmBtn = false
            }
            /* 出现了一些很麻烦且不影响功能的BUG， 先放一放 */
            console.clear()
          })
        }
      })

    },
    resetForm() {
      this.form = {
        id: undefined,
        picture: undefined,
        name: undefined,
        effect_picture: undefined,
        is_free: 0,
        sell_status: 1,
        day_price: [
          { day: 0, price: 0 }
        ]
      }
      this.pictureList = []
      this.pictureList_eff = []
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}


</style>
